package com.mspbots.rule.exceptions.triggerEscalation;

import cn.hutool.core.util.StrUtil;
import com.mspbots.cw.request.MessagesDTO;
import com.mspbots.cw.request.TenantUserDTO;
import com.mspbots.cw.request.TriggerEscalationDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Dennis
 */
@Slf4j
@Rule(name = "TriggerEscalationUser", description = "Send different messages to different user according to Trigger times")
public class TriggerEscalationUser extends TriggerEscalationBaseRule {

    @Condition
    public boolean condition(@Fact(FACT) TriggerEscalationDTO entry) {
        try {
            if (!setUserMapping(entry.getUserId(), entry.getTenantId()) || super.checkEscalationUser(entry)) {
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("TriggerEscalationRule execute error : {}", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    @Action
    public void action(@Fact(FACT) TriggerEscalationDTO entry) {
        TenantUserDTO tenantUserDTO = tenantUserService.findById(entry.getUserId());
        String template = null;
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            template = new String(decoder.decode(entry.getTemplate().getBytes()), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        tenantUserMappingDTO = this.tenantUserMappingService.findByTenantUser(entry.getTenantId(), entry.getUserId());
        MessagesDTO messages = new MessagesDTO();
        messages.setUserId(entry.getUserId());
//        messages.setBusinessId(900 + entry.getRuleId() + entry.getUserId());
        messages.setTeamsUserId(tenantUserMappingDTO.getTeamsUserId());
        messages.setRuleId(entry.getRuleId());
        messages.setEscalation(true);
        messages.setTenantId(entry.getTenantId());
        messages.setStatus("Ready");
        messages.setForwardStatus("Ready");
        messages.setType("user");

        Map<String, Object> params = new HashMap<>();
        if (!StringUtils.isEmpty(tenantUserDTO.getManager())) {
            TenantUserDTO tenantUserDTOName = tenantUserService.findById(tenantUserDTO.getManager());
            params.put("MANAGER", tenantUserDTOName.getFirstname() + " " + tenantUserDTOName.getLastname());
        }

        params.put("USER", tenantUserDTO.getFirstname());
        params.put("TRIGGERNAME", "<span style='color:#FF7F00;font-weight:bold'>\"" + entry.getName().replaceAll("(?=(?!^)[A-Z])", " ") + "\"</span>");
        params.put("TIMES", entry.getTimes());
        params.put("NEXTIMES", entry.getNextimes());
        String message = StrUtil.format(template, params);
//        messages.setMessage(message);
        messages.setMessage(message + escalationDetial(entry.getUserId(), entry.getRuleId(), tenantUserService, tenantUserMappingDTO));
        messages.setCreateDate(LocalDateTime.now());
        messages.setExpireDate(messages.getCreateDate().plusHours(12));
        messages.setBusinessType("escalationUser");
        MessagesDTO messagesResult = messagesService.insert(messages);
        if (messagesResult != null) {
//                messageProducer.produce(messagesResult);
        }
    }

}
